import { lazy, PureComponent, Suspense } from 'react'
import { Route, Switch } from 'react-router-dom'
import Header from './components/Header';
import Home from './pages/Home'
import { connect } from 'react-redux';
import * as action from './actions/user'
import Auth from './Auth'
import { getData } from './utils/locationStorage';

const Login = lazy(() => import('./pages/Login'))
const Regist = lazy(() => import('./pages/Regist'))
const Profile = lazy(() => import('./pages/Profile'))
const Setting = lazy(() => import('./pages/Setting'))
const ArticleNew = lazy(() => import('./pages/ArticleNew'))
const ArticleEdit = lazy(() => import('./pages/ArticlelEdit'))
const Article = lazy(() => import('./pages/Article'))

//问题： 页面加载慢
// 代码分割 => 并行 动态加载=> react 懒加载
// 页面无关的组件=>拆分成新的buddle=>当无关的组件被渲染的时候 才会下载到本地=>动态渲染
// 具体实现： React.lazy + import =>动态加载  ； Suspense 组件： 异步加载资源 显示友好信息

class App extends PureComponent {

  render() {
    const { currentUser } = this.props
    // console.log("APP-currentUser",this.props.currentUser);
    return (
      <div >
        {/* 应用头部Header */}
        <Header currentUser={currentUser} />

        {/* 主题页面 */}
        <Suspense fallback={<p>loading...</p>}>
          <Switch>
            <Route path="/" component={Home} exact />
            <Route path="/login" component={Login} />
            <Route path="/regist" component={Regist} />
            <Auth currentUser={currentUser}>
              <Switch>
                <Route path="/setting" component={Setting} />
                <Route path="/article/new" component={ArticleNew} />
                <Route path="/article/edit/:slug" component={ArticleEdit} />
                <Route path="/article/:slug" component={Article} />
                <Route path="/profile/:username" component={Profile} />
              </Switch>
            </Auth>
          </Switch>
        </Suspense>
      </div>
    );
  }

  componentDidMount() {
    //获取本地用户信息
    // const currentUser=getData('currentUser')
    // console.log("local-----",currentUser);
    // if(currentUser){
    // this.props.syncUser(currentUser)
    // }
  }

}

const mapState = state => {
  // console.log(state.user);
  return { currentUser: state.user.currentUser }
}

//同步本地用户信息
const mapDispatch = dispatch => ({
  syncUser: (user) => dispatch(action.userSyncResult(user))
})
export default connect(mapState, mapDispatch)(App);
// export default App
